<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

class CampaignAction extends NewzanAction
{
    public function manage()
    {
        $this->loadJS('template', 'rptchart', 'jquery.alimama' ,'custom.appbar', 'daterangepicker', 'date', "manage",
            "component/component.action.log", "campaign/detail", "campaign/info", "campaign/adgroups",
            "settings/area", "settings/schedule", "campaign/platform");
        $campaign_id = (int) $this->_get("campaign_id");
        if(!$campaign_id || !is_int( $campaign_id ) ){
            $this->error("参数错误");
        }
        $campaignMdl = D("Campaign");
        $campaign = $campaignMdl->getCampaignById( $this->me["user_id"] ,$campaign_id  , false);
        if(!$campaign){
        	$this->error("该推广计划不存在");
        }
        $this->campaign = $campaign["campaign"];
        $this->display("manage");
    }
    
    public function setStatus()
    {
        $user_id = $this->me['user_id'];
        $campaign_id = $this->_post('campaign_id');
        $campaign_title = $this->_post('campaign_title');
        $campaign_online = $this->_post('campaign_online');
        $campaign_online = ($campaign_online && $campaign_online == 'online') ? 'online' : 'offline';

        ParamsCheckUtils::checkNumeric($campaign_id  , '推广计划参数输入错误');
        ParamsCheckUtils::checkNULL($campaign_title , '推广计划标题不能为空');

        $res = array(
                'status' => 0,
                'msg' => '未知错误'
            );

        $campaignMdl = new CampaignModel();
        $campaign = $campaignMdl->getCampaignById($user_id, $campaign_id, false);
        if(!$campaign) {
            throw new TopClientException('推广计划不存在.', RetStatus::TOP_API_ERR);
        }

        if($campaign['online_status'] != $campaign_online) {
            $status = array(
                'campaign_id' => $campaign_id,
                'title' => $campaign_title,
                'online_status' => $campaign_online
            );
        
            $campaign = $campaignMdl->updateCampaignStatus($user_id, $campaign_id, $status);
            if($campaign['online_status'] == $campaign_online) {
                $res['status'] = 1;
                $res['msg'] = '修改成功';
            } else {
                $res['msg'] = '修改失败';
            }
        } else {
            $res['msg'] = '没有变化';
        }
        $this->display_json($res);
    }
    
    /**
     * 修改一个推广计划的日限额
     */
    public function update()
    {
		$user_id = $this->me['user_id'];
		$campaign_id = $this->_param('campaign_id');
		$campaign_title = $this->_param('campaign_title');
		$campaign_online = $this->_param('campaign_online');
        $campaign_status = $this->_param('campaign_status');
        $keyword_limit = $this->_param('keyword_limit');
        $keyword_limit *= 100;
		$campaign_online = $campaign_online ? 'online' : 'offline';
        if($campaign_status){
            $campaign_online = $campaign_online;
        }
		$new_budget = $this->_param('budget');
		//参数检查
		ParamsCheckUtils::checkNumeric($campaign_id  , '推广计划参数输入错误');
		ParamsCheckUtils::checkMinValue($new_budget, 30 , '推广计划日限额必须为整数且大于30元');
		ParamsCheckUtils::checkNULL($campaign_title , '推广计划标题不能为空');
		ParamsCheckUtils::checkMaxLength($campaign_title, 50 , '推广计划标题不得超过20个字');
        if( $keyword_limit >0 ){
		    ParamsCheckUtils::checkMinValue($keyword_limit, 5 , '自动推广关键词限价不得小于0.05元');
        }
    		
		$campaignMdl = new CampaignModel();
		$campaign = $campaignMdl->getCampaignById($user_id, $campaign_id, false);
		if(!$campaign) {
			throw new TopClientException('推广计划不存在.', RetStatus::TOP_API_ERR);
		}
    		
        //修改限价
        $oriKeywordLimit = $campaignMdl->where( array('campaign_id' => $campaign_id) )->getField('limit');
        if($oriKeywordLimit != $keyword_limit) {
            $campaignMdl->where( 'campaign_id =' . $campaign_id )->save( array('limit' => $keyword_limit) );
            //$oriCampWordLimit = D('auto_pro_product_queue')->where( 'campaign_id =' . $campaign_id)->getField('default_price');
            D('auto_pro_product_queue')->where( 'campaign_id =' . $campaign_id)->save( array('default_price' => $keyword_limit ) );
            //加限价后立即更新生效 
            if($keyword_limit > 0 && ($keyword_limit < $oriKeywordLimit||$oriKeywordLimit==0)) {
                $keywordMdl=new KeywordModel();
                $adgroupMdl=new AdgroupModel();
                //get all auto adgroups in the campaign
                $adgroups=$adgroupMdl->where(array('user_id' => $user_id, "campaign_id" => $campaign_id,"drive_type"=>1))->select();
                foreach($adgroups as $adgroup){       	
                    $keywordMdl->updateKeywordsPriceToLimit($user_id,$adgroup['adgroup_id'],$keyword_limit);
                }
            }
        }
		//如果budget被修改了
		if( $campaign['budget'] != $new_budget) {
		    $res = $campaignMdl->updateCampaignBudget($user_id, $campaign_id, $new_budget);
		}
    		
		//如果线上线下状态被修改了或者title被修改了
		if(($campaign['title'] != $campaign_title) || ($campaign['online_status'] != $campaign_online)) {
		    $status = array(
   					'campaign_id' => $campaign_id,
   					'title' => $campaign_title,
   					'online_status' => $campaign_online
   				);
    		$campaign = $campaignMdl->updateCampaignStatus($user_id, $campaign_id, $status);
		}

		$this->display_json( array('campaign' => $campaign_id , 'result' => ($campaign ? true : false) ), $campaign ? RetStatus::OK : RetStatus::TOP_API_ERR);
    }
   
    public function review()
    {
    	$campaign_id = (int) $this->_get("campaign_id");
    
    	if(!$campaign_id || !is_int( $campaign_id ) ){
    		$this->error("参数错误");
    	}
    
    	$campaignMdl = D("Campaign");
    	$campaign = $campaignMdl->getCampaignById( $this->me["user_id"] ,$campaign_id  , false);
    	if(!$campaign){
    		$this->error("该推广计划不存在");
    	}
    	
    	$rptCampaignMdl = D('RptCampaign');
    	$from = date("Y-m-d", time() - 7 * 86400);
    	$to = date("Y-m-d", time() - 86400);
    	$rpt = $rptCampaignMdl->getAllCampaignsStat($campaign_id , 'all' , 
    			$from, $to, "summary,series" );
    	$labels = RptBaseModel::$LABELS;
    
    	$stats = array();
    	foreach($rpt["summary"] as $k => $v){
    		if(!isset($labels[$k]))
    			continue;
    		$stats[$k] = array(
    				'num' => ($k=='ctr' ? "$v%" : $v),
    				'label' => $labels[$k],
    		);
    	    $stats[$k]["series"] = join( ',', array_column($rpt['series'][ $labels[$k] ], 1) );
    	}
    
    	// 设置stats显示的顺序
    	$this->order_list = array(
    			'impressions', 'cvr',
    			'click', 'ctr',
    			'cost', 'cpc',
    			'direct_pay', 'indirect_pay',
    			'sales', 'roi',
    		//	'fav_shop_count', 'fav_item_count',
    	);
    	$this->stats = $stats;
    	$this->campaign = $campaign["campaign"];
		$this->online_status = $this->campaign['online_status'];
		$this->from = $from;
		$this->to = $to;
    	$this->display();
    }
    
    public function saveplatform()
    {
    	$user_id = $this->me['user_id'];
    	$campaignMdl = new CampaignModel();
        $campaign_id = $this->_param('campaign_id');
    		
    	//修改平台投放状态
    	$search_channels = $_POST['search_channels'];
    	$nonsearch_channels = $_POST['nonsearch_channels'];
        $outside_discount = intval($_POST['outside_discount']);
    	$mobile_discount = intval($_POST['mobile_discount']);
    	if($outside_discount < 1 || $outside_discount > 200) {
            $this->display_json(array("result" => false, 'msg' =>'站外折扣必须在1%到200%之间.'), RetStatus::INNER_ERR);
        }
        if($mobile_discount < 1 || $mobile_discount > 400) {
    		$this->display_json(array("result" => false, 'msg' =>'移动折扣必须在1%到400%之间.'), RetStatus::INNER_ERR);
    	}
    	
    	$campaign_platform = array(
    			'search_channels' => implode(',' , array_filter($search_channels)),
    			'outside_discount' => $outside_discount,
                'mobile_discount' => $mobile_discount
    	);
    	if($nonsearch_channels) {
    		if(in_array(2,$nonsearch_channels) && !in_array(2,$search_channels)){
    			$this->display_json(array("result" => false, 'msg' => '您只有投放淘宝站内的定向推广后，才能选择投放淘宝站外的定向推广.'), RetStatus::INNER_ERR);
    		}
    		$campaign_platform['nonsearch_channels'] = implode(',' , array_filter($nonsearch_channels));
    	}
    	try {
    		$res = $campaignMdl->updateCampaignPlatform($user_id, $campaign_id , $campaign_platform);
	    	
	    	if($res) {
	    		$this->display_json( array( 'campaign' => $res , 'result' => true ) );
	    	} else {
	    		$this->display_json(array("result" => false, 'msg' => '没有要修改的值.'), RetStatus::INNER_ERR);
	    	}
    	} catch (Exception $e) {
   			if($e instanceof TopClientException) {
   				$exObj = json_decode($e->getMessage(), true);
   				$this->display_json(array("result" => false, 'msg' => $exObj['error_response']['sub_msg']), RetStatus::TOP_API_ERR);
   			} else {
   				$this->display_json(array("result" => false, 'msg' => '内部错误.'), RetStatus::INNER_ERR);	
   			}
   		}
    }
    
    /**
     * 投放平台设置
     */
    public function platform()
    {
    	$user_id = $this->me['user_id'];
    	$campaignMdl = new CampaignModel();
    	
	    	//     	$this->loadJS('jquery.sparkline.min' , 'custom.currency' , 'custom.appbar');
	    	$campaign_id = (int) $this->_get("campaign_id");
	    
	    	if(!$campaign_id || !is_int( $campaign_id ) ){
	    		$this->error("参数错误");
	    	}
	    
	    	$campaign = $campaignMdl->getCampaignById( $this->me["user_id"] ,$campaign_id  , false);
	    	if(!$campaign){
	    		$this->error("该推广计划不存在");
	    	}
	    	//得到设置的投放平台
	    	$campaign_platform = json_decode($campaign['campaign']['platform'], true);

            $this->search_channels = array(
                                            'c1' => in_array( 1,  $campaign_platform['search_channels']['number']) ? 1 : 0,
                                            'c2' => in_array( 2,  $campaign_platform['search_channels']['number']) ? 1 : 0,
                                            'c4' => in_array( 4,  $campaign_platform['search_channels']['number']) ? 1 : 0,
                                            'c8' => in_array( 8,  $campaign_platform['search_channels']['number']) ? 1 : 0,
                                            'c16' => in_array( 16,  $campaign_platform['search_channels']['number']) ? 1 : 0,
                                        );

            $this->nonsearch_channels = array(
                                                    'c1' => in_array( 1,  $campaign_platform['nonsearch_channels']['number']) ? 1 : 0,
                                                    'c2' => in_array( 2,  $campaign_platform['nonsearch_channels']['number']) ? 1 : 0,
                                                    'c4' => in_array( 4,  $campaign_platform['nonsearch_channels']['number']) ? 1 : 0,
                                                    'c8' => in_array( 8,  $campaign_platform['nonsearch_channels']['number']) ? 1 : 0,
                                                    'c16' => in_array( 16,  $campaign_platform['nonsearch_channels']['number']) ? 1 : 0,
                                            );
            $this->outside_discount = $campaign_platform['outside_discount'];
	    	$this->mobile_discount = $campaign_platform['mobile_discount'];
	    	$this->campaign = $campaign["campaign"];
	    	$this->online_status = $this->campaign['online_status'];

            $this->s = json_encode($this->search_channels);
            $this->n = json_encode($this->nonsearch_channels);
	    	$this->display();
    }
    
    public function adgroups()
    {
    	$format = $this->_get('format');
    	$from = $this->_get('from');
    	$to = $this->_get('to');
        $sort['sort'] = $this->_get('sort');
        $sort['sort'] = $sort['sort'] ? trim($sort['sort']) : 'status';
        $sort['asc'] = $this->_get('asc');
        $sort['asc'] = $sort['asc'] ? trim($sort['asc']) : 'desc';
        $campaign_ids = array();

        $campaign_id = $this->_get('campaign_id');
        if($campaign_id){
            $campaign_ids[] = $campaign_id;
        }
        if($this->_get('campaign_ids')){
            $ids = explode(',', $this->_get('campaign_ids'));
            foreach($ids as $id){
                $campaign_ids[] = $id;
            }
        }
      	$campaignMdl = new CampaignModel();
        $adgroupMdl = new AdgroupModel();
        $productMdl = new ProductModel();

        $all_adgroups = array();
        foreach($campaign_ids as $campaign_id){
            $campaign = $campaignMdl->getCampaignById($this->me['user_id'] , $campaign_id,false);
            $from = $from ? $from : date("Y-m-d", strtotime("-1 day"));
            $to = $to ? $to : date("Y-m-d", strtotime("-1 day"));
            $adgroups = $adgroupMdl->getCampaignsAdgroups($this->me["user_id"] , $campaign_id ,
                true, $from, $to,true, 0, 0, $sort);
            $ids=array();
            if($adgroups) {
                foreach($adgroups as $ad){
                    $ids[]=$ad['num_iid'];
                }
            }
            $products=$productMdl->getProductByIds($this->me["user_id"] ,$ids, false);
            $auto_queue=array();
            if(!empty($adgroups)){
                $autoMdl = D('auto_pro_product_queue');
                $adgroup_list=implode(',',array_keys($adgroups));
                $auto_queue = $autoMdl->field('adgroup_id,type')->where('adgroup_id in ('.$adgroup_list.')')->select();
                foreach( $auto_queue as &$aq){
                    $auto_queue[$aq['adgroup_id']] = $aq;
                    unset($aq);
                }
            }
            $status_str=$campaign&&$campaign['campaign']['online_status']=='offline'?'推广计划暂停':'推广中';
            if($adgroups) {
                foreach($adgroups as &$ad){
                    $ad['drive_type_str'] = $ad['drive_type'] == 0 ? '手动开车' : '自动开车';
                    if(!isset($products[(string)$ad['num_iid']])){
                        $ad['status_str'] ='商品已下架';
                    }else if( $ad['online_status'] != 'online' || $ad['offline_type'] != 'online' ){
                        $ad['status_str'] =  $ad['offline_type'] != 'online' ? '审核下线' : '暂停中';
                    }else{
                        $ad['status_str'] = $status_str;
                    }
                    $all_adgroups[] = $ad;
                }
            }
        }

        $this->adgroups = $all_adgroups;
        $this->campaign_id = $campaign_id;
        $this->campaign_ids = $campaign_ids;
        $this->from = $from;
        $this->to = $to;
        if( $format == 'ajax'){
            $this->display('Ajax:campaign_adgroups');
        } elseif ( $format == 'json' ) {
            $this->display_json($all_adgroups);
        } else {
            $this->display();
        }
    }

    /**
     * 显示推广计划的所有操作记录，包括推广组的修改，关键词的增删改等
     * TODO 第一页的时候查询数据库, 并且缓存. 第二页开始只从缓存读.
     */
    public function log()
    {
	    $campaign_id = $this->_get('campaign_id');
		$adgroup_id = $this->_get('adgroup_id');
        $page = $page ? $page : 1;
        $pagesize = $this->_get('pagesize');
        $format = $this->_get('format');
        $format = $format ? $format : 'page';

        if( $format == 'page' ){
            $this->campaign_id = $campaign_id;
            $this->page = $page;
            $this->display(); 
        }else{
            $page = $this->_get('page');
            //1. get adgroup logs
            $campaignMdl = new CampaignModel();
            $campaign_logs = $campaignMdl->getLogs($this->me['user_id'] , 'campaign_id' , $campaign_id, null, null, true);
            $logs = $campaign_logs;
            $campaign_logs_count = count( $campaign_logs );
            //get adgroups id inside this campaign
            $adgroup_ids = M('adgroups')->where( 'campaign_id = ' .$campaign_id )->getField('adgroup_id' , true);
            if( empty( $adgroup_ids ) ){
                $adgroup_ids = array(0); 
            }else{
            //2. get adgroup keyword log
            $keywordMdl = new KeywordModel();
            $keyword_logs = $keywordMdl->getLogs($this->me['user_id'] , 'adgroup_id' , $adgroup_ids );
            $logs = array_merge($keyword_logs, $logs);
            $Keyword_logs_count = count( $keyword_logs );
            //3. get creative logs
            $creativeMdl = new CreativeModel();
            $creative_logs = $creativeMdl->getLogs($this->me['user_id'], 'adgroup_id', $adgroup_ids );
            $creative_logs_count = count( $creative_logs );
            //$logs += $creative_logs;
            $logs = array_merge($logs, $creative_logs);
            }

            $date_logs = array();
            foreach($logs as $log){
                if( !isset( $date_logs[$log['updated_date']] ) ){
                    $date_logs[ $log['updated_date'] ] = array();
                } 
                $date_logs[ $log['updated_date'] ][] = $log;
            }
             //4. sort logs
             usort( $date_logs , uc_cmp_log_desc);
             //krsort( $date_logs , false);
             $paged_logs = array_slice( $logs, $pagesize * ($page - 1) , $pagesize);
             $has_next = ($pagesize * $page) < count($logs) ? 1 : 0;
             $res = array(
                'logs' => $paged_logs,
                'campaign_logs_count' => $campaign_logs_count ? $campaign_logs_count : 0,
                'keyword_logs_count' => $keyword_logs_count ? $keyword_logs_count : 0,
                'creative_logs_count' => $creative_logs_count ? $creative_logs_count : 0,
                'current_page' => $page,
                'has_next' => $has_next
             );
             //$this->logs = $date_logs;
             $this->display_json($res);
        }
    }
    
    public function products()
    {
        $page = (int) $this->_get('current_page');
        $selectAll = $this->_get('select');
        $pagesize = (int) $this->_get('page_size');
        $pagesize = $pagesize ? $pagesize : 20;
        $keyword = $this->_get('keyword');
        $cid = $this->_get('cid');
        $page = $page ? $page : 1;
        $type = $this->_get("type");
        $type = $type ? $type : 1;
        $selectAll = in_array(strtolower($selectAll), array('true', 'false')) ? true : false;
        $order_field = $this->_get('order_field');
        $order_by = $this->_get('order_by');
        $productMdl = new ProductModel();
        $with_imgs = (int) $this->_get('with_imgs');
       	$products = $productMdl->getUserProducts($this->me["user_id"], $keyword , $cid , $page ,  $pagesize, $order_field, $order_by, null,$selectAll);
       	//if with imgs or not
       	if( $with_imgs ){
       		foreach( $products['products'] as &$p){
       			$item_imgs=json_decode($p['item_imgs'] , true);
       			$p['imgs'] = $item_imgs['item_img'];
       			if(empty($p['imgs'])){
       				$p['imgs'][] = array(
       						'url' => $p['pic_url']
       				);
       			}
       		}       		 
       	}

       	$this->display_json( array( 'products' => $products['products'] , 'total' => $products['total'] , 'size' => $products['size'] ));
    }
    
    public function campaigns_opts()
    {
        $this->product_id = (float) $this->_get('product_id');
        $this->campaign_id = $this->_get('campaign_id');
        $campaign_obj = D('Campaign');
        $campaign = $campaign_obj->getCampaignById($this->me['user_id'], $this->campaign_id);
        $this->campaign = $campaign['campaign'];
        $this->display();
    }
    
    public function addproduct()
    {
        $this->loadJS('jquery.cookie', "custom.currency");
        $product_id = $this->_get('product_id');
        $product = D("Products")->where( array("product_id" => $product_id , "user_id" => $this->me["user_id"]))->find();
        $this->product = $product;
        $campaign_obj = D('Campaign');
        $campaigns = $campaign_obj->getCampaigns($this->me['user_id']);
        $this->campaigns = $campaigns["campaigns"];
        $this->display();
    }
    
    /**
     * 获取推广计划的基本信息和已经提交到该推广计划的产品ID列表.
     */
    public function info()
    {
        $campaign_id = $this->_get('campaign_id');
        $campaignMdl = new CampaignModel();
        $campaign = $campaignMdl->getCampaignInfo($this->me["user_id"] , $campaign_id);
        $data = array();
        if($campaign) {
            $existent_products = D('Adgroup')->getCampaignsAdgroups($this->me['user_id'], $campaign_id, false);
			$existent_products = array_column($existent_products, 'num_iid');
            $data = array(
                'budget' => $campaign["budget"],
                'limit' => "0",
                'title' => $campaign["title"],
                'products' => $existent_products
            );
        }
        $this->display_json($data);
    }
    
    public function createcampaign()
    {
        try{
            $campaign_obj = D('Campaign');
            $campaigns = $campaign_obj->getCampaigns($this->me['user_id']);        
            $num =count($campaigns);
            if($num==8){
                $this->display_json( array('result' => false , 'msg' => "标准推广计划数量达到上限，最多创建8个" ));
            }else{
                $title=$_POST['title'].'云智投';
                $texit=false;
                foreach($campaigns as $campaign){
                    if($campaign['title']==$title){
                        $texit=true;
                        break;
                    }
                }
                if($title==''){
                    $this->display_json( array('result' => false , 'msg' => "推广计划名称不能为空" ));
                }else if(strlen($title)>60){
                    $this->display_json( array('result' => false , 'msg' => "推广计划名称不能多于20字符" ));
                }else if($texit) {
                    $this->display_json( array('result' => false , 'msg' => "推广计划'$title'已经存在" ));
                }else{
                    $campaignMdl = new CampaignModel();      	
                    try{
                        $result = $campaignMdl->createCampaign($title);
                        $syncMdl=new SyncModel();
                        $syncMdl->syncCampaign($this->me['user_id']);
                    }catch (Exception $e) {
                        $rep=json_decode($e->getMessage(),true);
                        //  if($rep())
                        $this->display_json( array('result' => false , 'msg' => $rep['error_response']['sub_msg']));
                    }
                    $this->display_json( array('result' => true , 'msg' => "新建推广计划成功！", 'campaign'=>$result));
                }
            }
        }catch(Exception $e) {
            return $egetMessage();
        }
    }
}
